﻿using Assets.Scripts.DL.Consts;
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Pool;

namespace Assets.Scripts.DL.Mgrs {
	public class ObjectPool : MonoBehaviour {
		[SerializeField] int _maxQueueCnt = 20;

		public static ObjectPool Instance;

		public Dictionary<string, GameObject> PrefabDic = new Dictionary<string, GameObject>();
		public Dictionary<string, Queue<GameObject>> ObjectDic = new Dictionary<string, Queue<GameObject>>();

		private void Awake() {
			Init();
			Instance = this;
		}

		private void Init() {
			var prefabs = ResLoader.LoadAllPrefab(PathStr.ObjectPoolPrefab);

			foreach (var obj in prefabs) {
				PrefabDic.Add(obj.name, obj);
				ObjectDic[obj.name] = new Queue<GameObject> { };
			}
		}

		public GameObject GetObject(string name, Transform trans = null) {
#if UNITY_EDITOR
			if (!PrefabDic.ContainsKey(name)) {
				Debug.Log($"Not found {name} In pool");
			}
#endif

			GameObject tmp;
			// 如果池子内有物体，从池子取出一个物体
			if (ObjectDic[name].Count > 0) {
				// 将对象出队
				tmp = ObjectDic[name].Dequeue();
				tmp.SetActive(true);
			}
			// 如果池子中没有物体，直接新建一个物体
			else {
				trans = trans != null ? trans : transform; //有的ui可能需要设置transform
				tmp = Instantiate(PrefabDic[name], trans);
			}
			return tmp;
		}

		public void RecycleObject(string name, GameObject obj) {
#if UNITY_EDITOR
			if (!PrefabDic.ContainsKey(name)) {
				Debug.Log($"Not found {name} In pool");
			}
#endif
			// 池子中的物体数目不超过最大容量
			if (ObjectDic[name].Count <= _maxQueueCnt) {
				// 该对象没有在队列中
				if (!ObjectDic[name].Contains(obj)) {
					// 将对象入队
					ObjectDic[name].Enqueue(obj);
					obj.SetActive(false);
				}
			}
			// 超过最大容量就销毁
			else {
				Destroy(obj);
			}

		}


	}
}
